package utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import au.AU.ActiveLabel;

public class Utils {

	public static double[] mergeArrays(double[] a, double[] b) {
		double[] res = new double[a.length + b.length];
		for (int i = 0; i < a.length; i++)
			res[i] = a[i];
		for (int i = 0; i < b.length; i++)
			res[a.length + i] = b[i];
		return res;
	}

	public static void writeFile(File file, String line) {
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				throw new RuntimeException("Log file " + file.getName() + " cannot be created.");
			}
		}

		try {
			BufferedWriter bw = new BufferedWriter(new FileWriter(file, true));
			bw.write(line);
			bw.newLine();
			bw.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void writeFile(File file, Integer label, double[] vector) {
		String line = String.valueOf(label) + " ";
		for (int i = 0; i < vector.length; i++)
			line += i + 1 + ":" + vector[i] + " ";
		writeFile(file, line);
	}

	public static double avg(double[] es) {
		double res = 0;
		for (Double d : es)
			res += d;
		res = res / es.length;
		return res;
	}

	public static String runCmd(String cmd) {

		try {
			Runtime run = Runtime.getRuntime();
			Process pr;
			pr = run.exec(cmd);
			pr.waitFor();
			BufferedReader buf = new BufferedReader(new InputStreamReader(
					pr.getInputStream()));
			String line;
			String out = "";
			while ((line = buf.readLine()) != null) {
				out += line + "\n";
			}
			return out;

		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return null;

	}
	
	public static List<String> labelsToStringList() {
		List<String> res = new ArrayList<String>();
		for(ActiveLabel label: ActiveLabel.values()) {
			res.add(label.toString());
		}
		return res;
	}

	public static void clearFile(File f) {
		PrintWriter writer;
		try {
			writer = new PrintWriter(f);
			writer.print("");
			writer.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static String wrapFSDKAPIKey() throws IOException {
		BufferedReader buf = new BufferedReader(new FileReader("private/fsdk_api_key"));
		return buf.readLine();
	}
	
}
